package m.system.util;

import m.common.model.DictionaryModel;
import m.common.model.FieldMeta;
import m.common.model.Model;
import m.common.model.config.ModelConfig;

import java.util.*;

public class DictionaryUtil {
	//----------------dictType   dataValue   dataName
	protected final static Map<String,Map<String,String>> map= new HashMap<>();
	protected final static Map<String,Map<String,String>> titleMap= new HashMap<>();
	protected final static Map<String,String[]> valuesMap= new HashMap<>();
	protected final static Map<String,Set<String>> linkTypeMap=new HashMap<>();
	private static void addLinkType(String pt,String st){
		Set<String> set=linkTypeMap.get(pt);
		if(null==set){
			linkTypeMap.put(pt,new HashSet<>());
			set=linkTypeMap.get(pt);
		}
		set.add(st);
	}
	private static void initDict(String dictType){
		Map<String,String> dmap = new LinkedHashMap<>();
		Map<String,String> tmap = new LinkedHashMap<>();
		List<String> vlist=new ArrayList<>();
		try {
			if (dictType.indexOf("!") > 0) {
				String[] arr = dictType.split("!");
				Model mc = ClassUtil.newInstance(arr[0]);
				FieldMeta fm = ModelConfig.getFieldMetaMap(mc.getClass()).get(arr[1]);
				String dt=fm.dictType();
				String dp=fm.dictOption();
				if (!StringUtil.isSpace(dt)) {
					dmap = init(dt);
					tmap = titleMap.get(dt);
					vlist = Arrays.asList(valuesMap.get(dt));
					if (dt.indexOf("!") > 0) {
						addLinkType(dt.split("!")[0], dictType);
					} else {
						addLinkType(dt.split(":")[0], dictType);
					}
				} else if (!StringUtil.isSpace(dp)) {
					String[] opts = dp.split(",");
					for (String str : opts) {
						if (StringUtil.noSpace(str).indexOf(":") > 0) {
							String[] tmp = str.split(":");
							dmap.put(tmp[0], tmp[1] + "|Y|");
							tmap.put(tmp[0], tmp[1]);
							vlist.add(tmp[0]);
						}
					}
				}
			} else if(dictType.startsWith("@")){
				String[] arr=dictType.substring(1).split(",");
				for(String dd : arr){
					String[] d=dd.split(":");
					dmap.put(d[0], d[1] + "|Y|");
					tmap.put(d[0], d[1]);
					vlist.add(d[0]);
				}
			} else {
				String[] arr = dictType.split(":");
				DictionaryModel dict = ClassUtil.newInstance(arr[0]);
				List<DictionaryModel> dlist = dict.getCacheList(arr.length > 1 ? arr[1] : "");
				for (DictionaryModel dd : dlist) {
					dmap.put(dd.getDictValue(), dd.getDictName() + "|" + dd.getDictStatus()+ "|"+dd.getDictParentOid());
					tmap.put(dd.getDictValue(), dd.getDictName());
					vlist.add(dd.getDictValue());
				}
			}
		} catch (Exception e) {
			SystemUtil.printlnIf(true,"字典初始化错误",e.getMessage());
			e.printStackTrace();
		}
		map.put(dictType, dmap);
		titleMap.put(dictType, tmap);
		valuesMap.put(dictType,vlist.toArray(new String[0]));
		SystemUtil.printlnIf(true,"初始化字典",dictType);
	}
	/**
	 * 初始化字典
	 * 类属性:格式填(类全名!属性)
	 * 自定义字典:格式填@开头(@Y:是,N:否)
	 * 类缓存列表:格式填(类全名:参数)或者(类全名) 参数根据缓存列表定义设置
	 */
	protected static Map<String,String> init(String dictType){
		if(null==map.get(dictType)){
			synchronized (DictionaryUtil.class) {
				if(null==map.get(dictType)) {
					initDict(dictType);
				}
			}
		}
		return map.get(dictType);
	}
	/**
	 * 清除全部
	 */
	public static void clearAll(){
		map.clear();
		titleMap.clear();;
		valuesMap.clear();;
	}

	/**
	 * 清除 字典类
	 */
	public static void clear(Class<? extends DictionaryModel> clazz,String key){
		clear(clazz.getName()+":"+key);
	}
	/**
	 * 清除 缓存同步执行
	 */
	public static void clear(String dictType){
		if (dictType.indexOf("!") > 0) {
			map.put(dictType,null);
			titleMap.put(dictType,null);
			valuesMap.put(dictType,null);
		}else{
			String[] arr=dictType.split(":");
			clearLinkType(arr[0]);
			for(String k : map.keySet()){
				if(k.indexOf(arr[0])==0){
					map.put(k,null);
					titleMap.put(k,null);
					valuesMap.put(k,null);
				}
			}
		}
		SystemUtil.printlnIf(true,"清除字典",dictType);
	}
	private static void clearLinkType(String dictClass){
		if(null!=linkTypeMap.get(dictClass)) {
			for (String k : linkTypeMap.get(dictClass)) {
				clear(k);
			}
		}
	}
	/**
	 * 清除
	 */
	public static <T extends DictionaryModel> void clear(Class<T> clazz){
		clear(clazz.getName());
	}
	/**
	 * 获取字典名称
	 *  dictType 字典类型
	 *  dataValue 字典值
	 * 
	 */
	public static String getName(String dictType,String dataValue){
		if(null==dataValue){
			return "";
		}else{
			return getName(dictType,dataValue.split(","));
		}
	}
	public static String getName(String dictType,Object dataValue){
		if(null==dataValue){
			return "";
		}else if(dataValue.getClass().isArray()) {
			return getName(dictType, (String[])dataValue);
		}else{
			return getName(dictType, dataValue.toString());
		}
	}
	public static String getName(String dictType,String[] arr){
		init(dictType);
		Map<String,String> map=titleMap.get(dictType);
		List<String> list= new ArrayList<>();
		for(String s : arr){
			String v=map.get(s);
			list.add(null==v?s:v);
		}
		if(!list.isEmpty()){
			return ArrayUtil.connection(list.toArray(new String[]{}), ",");
		}else{
			return "";
		}
	}
	/**
	 * 获取对应字典下的所有字典值.
	 */
	public static Map<String,String> get(String dictType){
		init(dictType);
		return map.get(dictType);
	}
	/**
	 * 获取对应字典下的所有字典值. 不含状态和父节点
	 */
	public static Map<String,String> getTitle(String dictType){
		init(dictType);
		return titleMap.get(dictType);
	}

	/**
	 * 通过字典显示值，获取字典value
	 */
	public static String getValue(String dictType,String name){
		init(dictType);
		Map<String,String> map=getTitle(dictType);
		for(String key : map.keySet()){
			if(map.get(key).equals(name)){
				return key;
			}
		}
		return null;
	}

	/**
	 * 获取字典对应的所有value值，包含禁用的，可用于检测输入项
	 */
	public static String[] getValues(String dictType){
		init(dictType);
		return valuesMap.get(dictType);
	}
}
